package com.tarena.lbs.business.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.param.UserLocationParam;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Tag(name = "店铺相关功能接口")
@RestController
@Slf4j
public class StoreController {

    @DubboReference
    private UserApi userApi;
    @Autowired
    private StoreService storeService;
    @Operation(summary = "查询店铺列表")
    @PostMapping("/admin/basic/store/getAll")
    public Result<PageResult<StoreVO>> pageList(@RequestBody StoreQuery query)
        throws BusinessException {
        if (getUserIdFromHeader()==null){
            throw new RuntimeException("用户未登录");
        }
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("userPrincle:{}",userPrinciple);
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        userPrinciple.getRole();
        if (userPrinciple.getRole()!= Roles.SHOP){
            throw new RuntimeException("用户不是商家");
        }
        AdminDto adminDto=userApi.getAdminById(userPrinciple.getId());
        if (adminDto==null){
            throw new RuntimeException("商家信息为空");
        }
        query.setBusinessId(adminDto.getBusinessId());
        log.info("userRole:{}",userPrinciple.getRole());
        PageResult<StoreVO> pageResult = storeService.selectStore(query);
//        pageResult.setObjects(new ArrayList<>());
//        pageResult.setTotal(1L);
//        pageResult.setPageSize(1);
        return new Result(pageResult);
    }

    /**
     * 新增店铺
     * @param param
     * @return
     * @throws BusinessException
     */
    @Operation(summary = "新增店铺")
    @PostMapping("/admin/basic/store/add")
    public Result<Void> save(@RequestBody StoreParam param)
        throws BusinessException {
        return Result.success();
    }

    //查询 属于当前登录用户 所属商家 和满足区域条件的店铺列表
    @Operation(summary = "查询区域下的店铺列表")
    @PostMapping("/admin/basic/store/getStoreByCity")
    public Result<PageResult<StoreVO>> getStoreByCity(@RequestBody AreaStoreQuery query)
        throws BusinessException {
        log.info("地区参数:{}",query);
        if (getUserIdFromHeader()==null){
            throw new RuntimeException("用户未登录");
        }
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("userPrincle:{}",userPrinciple);
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        userPrinciple.getRole();
        if (userPrinciple.getRole()!= Roles.SHOP){
            throw new RuntimeException("用户不是商家");
        }
        AdminDto adminDto=userApi.getAdminById(userPrinciple.getId());
        if (adminDto==null){
            throw new RuntimeException("商家信息为空");
        }
        Integer businessId=adminDto.getBusinessId();
        log.info("userRole:{}",userPrinciple.getRole());
        PageResult<StoreVO> pageResult = storeService.selectStoreByAreaAndBusinessId(query,businessId);
        return new Result(pageResult);
    }
    //手机小程序定位上报
    @Operation(summary = "手机小程序定位上报")
    @PostMapping("/basic/store/location")
    public Result<Void> location(@RequestBody UserLocationParam param)
        throws BusinessException{
        return Result.success();
    }
    private Integer getUserIdFromHeader() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) return null;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("authorization");
            log.debug("tokenn:{}",token);
            if (StringUtils.isNotBlank(token)) {
                Integer number=parseUserIdFromToken(token);
                log.debug("用户number:{}",number);
                return number;
            }
            return null;
        } catch (Exception e) {
            log.error("从请求头获取用户ID失败", e);
            return null;
        }
    }
    private Integer parseUserIdFromToken(String token) {
        try {
            // JWT token 由三部分组成，用点分隔：Header.Payload.Signature
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                log.warn("JWT token 格式不正确");
                return null;
            }
            // 解码 Payload 部分 (Base64Url)
            String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
            // 解析 JSON payload
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode payloadNode = objectMapper.readTree(payload);
            // 根据你的 JWT 结构获取用户ID
            // 从你的 token 看，payload 包含一个 payload 字段，里面是用户信息
            if (payloadNode.has("payload")) {
                String innerPayload = payloadNode.get("payload").asText();
                JsonNode userInfo = objectMapper.readTree(innerPayload);

                if (userInfo.has("id")) {
                    return userInfo.get("id").asInt();
                }
            }
            // 或者直接查找 id 字段
            if (payloadNode.has("id")) {
                return payloadNode.get("id").asInt();
            }
            log.warn("在 JWT token 中未找到用户ID");
            return null;
        } catch (Exception e) {
            log.error("解析 JWT token 失败", e);
            return null;
        }
    }
}
